import { combineReducers, applyMiddleware, createStore, compose } from 'redux';
import promise from 'redux-promise';
import reduxThunk from 'redux-thunk';

import rootReducer from './reducer';

function createReducer(asyncReducers) {
  return combineReducers({
    ...rootReducer,
    ...asyncReducers
  });
}

export default function configureStore() {
  const composeEnhancers = 
    typeof window === 'object' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
      ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({})
      : compose;

  const enhancer = composeEnhancers(applyMiddleware(promise, reduxThunk));
  const store = createStore(createReducer(), enhancer);

  store.asyncReducers = {};
  
  store.injectReducer = (key, asyncReducer) => {
    store.asyncReducers[key] = asyncReducer;
    store.replaceReducer(createReducer(store.asyncReducers));
  }

  return store;
}

export const store = configureStore();
